<?php
namespace app\api\controller;

use \think\Controller;
use \think\Db;
class Index extends Base
{
    /**
     * 通用：第一次登录的弹出图片
     * type：1是用户端  2是商户端   3是业务端
     */
    public function tan()
    {
        header("Access-Control-Allow-Origin:*");
        extract(input());
        $data = Db::table('up_tan')->where('tan_id',$type)->find();
        return json_encode(['status'=>200,'msg'=>$data]);
    }

    /**
     * 首页展示离我最近的15个商家
     * @$page 分页
     * $lat,$lon
     * @return array 返回数组
     */
    public function index()
    {
		extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $where = array();
        $where['s_status'] = 1;//不能是信用太低的
        $where['s_admin'] = 1;//不能是关停的
        $where['s_join_end'] = array('>=',date('Y-m-d'));//到期时间大于今天
        if(isset($keyword) && $keyword){
            $where['s_name'] = array('like',"%$keyword%");
        }
//        $lat = '31.97582940293274';
//        $lon = '118.7714203586221';
//        $page = 1;
        $mile = Db::table('up_set_juli')->where('juli_id',1)->value('juli_value');
        $miles = (int)$mile*1000;
        $field = 's_id,s_thumb,s_name,s_pinlei,pl_image';
        $field .= ',ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(('.$lat.'* PI() / 180 - s_lat * PI() / 180) / 2),2) + COS('.$lat.' * PI() / 180) * COS(s_lat * PI() / 180) * POW(SIN(('.$lon.' * PI() / 180 - s_lon * PI() / 180) / 2),2))) * 1000) AS distance';
        $data = Db::table('up_shops')->alias('s')
            ->join('up_work_pl wp','s.s_pinlei_id=wp.pl_id','LEFT')
            ->field($field)
            ->where($where)
            ->having("distance <= $miles")
            ->order('distance ASC')
            ->page($page,15)
            ->select();
        $index = Db::table('up_tan')->where('tan_id',4)->find();
        return json_encode(['status'=>200,'msg'=>$data,'index'=>$index['tan_image']]);
    }
    /**
     * 某个商家详情——首页
     * s_id 商家id
     * lat lon
     * @return array 返回数组
     */
    public function shopInfo()
    {
        extract(input());
            $auth = $this->checkAll($user_id,$time,$value,$reqKey);
            if($auth == false){
                $returnData['status'] = 301;
                $returnData['msg'] = "Token失效！请重新登录！";
                return json_encode($returnData);
            }
        $advert = Db::table('up_shop_advert')
            ->where('adv_shopid', $s_id)
            ->select();
        $type = Db::table('up_shop_type')
            ->where('st_shopid', $s_id)
            ->order('st_order DESC')
            ->select();
        $good = Db::table('up_goods')
            ->where('g_shop', $s_id)
            ->where('g_status', 1)
            ->order('g_prcie_kill DESC,g_time DESC')//秒杀排在前面
//            ->page(1,12)
            ->select();
        //----------------加入购物车了没-----
        if($good){
            foreach ($good as $k=>$v){
                $good[$k]['haveNum'] = 0;
                $have = Db::table('up_shopping_car')
                    ->where('car_goodid', $v['g_id'])
                    ->where('car_userid', $user_id)
                    ->field('car_number')
                    ->find();
                if($have){
                    $good[$k]['haveNum'] = $have['car_number'];
                }
            }
        }
        //----------------加入购物车了没end-----
        $shop = Db::table('up_shops')
            ->where('s_id', $s_id)
            ->find();
        //------------------------------------------------
        $where = array();
        $where['s_status'] = 1;//不能是信用太低的
        if(isset($keyword) && $keyword){
            $where['s_name'] = array('like',"%$keyword%");
        }
        $mile = Db::table('up_set_juli')->where('juli_id',1)->value('juli_value');
        $miles = $mile*1000;
        $field = 's_id,s_thumb';
        $field .= ',ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(('.$lat.'* PI() / 180 - s_lat * PI() / 180) / 2),2) + COS('.$lat.' * PI() / 180) * COS(s_lat * PI() / 180) * POW(SIN(('.$lon.' * PI() / 180 - s_lon * PI() / 180) / 2),2))) * 1000) AS distance';
        $data = Db::table('up_shops')
            ->field($field)
            ->where($where)
            ->having("distance <= $miles")
            ->order('distance ASC')
            ->page(1,15)
            ->select();
        //------------------------------------------------
        return json_encode(['status'=>200,'advert'=>$advert,'type'=>$type,'good'=>$good,'shop'=>$shop,'data'=>$data]);
    }
    /**
     * 商户主页
     * s_id 商家id
     * @return array 返回数组
     */
    public function shopInfoMain()
    {
        extract(input());
        $auth = $this->checkAll($user_id, $time, $value, $reqKey);
        if ($auth == false) {
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        //1、商户主页
        $shop = Db::table('up_shops')
            ->where('s_id', $s_id)
            ->find();
        if ($shop['s_image']) {
            $shop['s_image'] = explode(',', $shop['s_image']);
        }
        $today = date('Y-m-d');
        //2-1、商户活动信息
        $active = Db::table('up_shop_active')
            ->where('sa_shopid', $s_id)
            ->where('sa_start', '<=',$today)
            ->where('sa_end', '>=',$today)
            ->find();
        //2-2、商户活动展示是否有抢购秒杀
        $kill = 0;
        $killhave = Db::table('up_goods')//存在即代表有抢购商品（秒杀）
            ->where('g_shop', $s_id)
            ->where('g_prcie_kill', '>',0)
            ->where('g_kill_start', '<=',$today)
            ->where('g_kill_end', '>=',$today)
            ->value('g_id');
        if($killhave){
            $kill = 1;
        }
        //3、此店铺的最新的一个评论
        $field = 'comment_id,comment_goodid,comment_user_id,comment_score,comment_content,comment_time';
        $field .= ',comment_username,comment_image,user_username,user_image';
        $pl = Db::table('up_good_comment')->alias('gc')
            ->join('up_u_user u','gc.comment_user_id=u.user_id','LEFT')
            ->where('comment_shopid', $s_id)
            ->order('comment_time DESC')
            ->field($field)
            ->find();
        return json_encode(['status'=>200,'shop'=>$shop,'active'=>$active,'kill'=>$kill,'pl'=>$pl]);
    }
    /**
     * 某个商家的某个类别的商品列表
     * s_id 商家id
     * type 商品类别
     * $keyword
     * @return array 返回数组
     */
    public function shopGoodList()
    {
        extract(input());
        $auth = $this->checkAll($user_id, $time, $value, $reqKey);
        if ($auth == false) {
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        //1、商品列表
        $where = array();
        if(isset($type) && $type){
            $where['g_type'] = $type;
        }
        $where['g_shop'] = $s_id;
        $where['g_status'] = 1;
        if(isset($keyword) && $keyword){
            $where['g_name'] = array('like',"%$keyword%");
        }
        $order = 'g_prcie_kill DESC';
        if(isset($price) && $price == 1){//1是高到低 2是低到高
            $order .= ',g_price_now DESC';
        }
        if(isset($price) && $price == 2){//1是高到低 2是低到高
            $order .= ',g_price_now ASC';
        }
        if(isset($sales) && $sales == 1){//1是高到低 2是低到高
            $order .= ',g_sale_num DESC';
        }
        if(isset($sales) && $sales == 2){//1是高到低 2是低到高
            $order .= ',g_sale_num ASC';
        }
        $order = trim($order,',');
        $good = Db::table('up_goods')//存在即代表有抢购商品（秒杀）
            ->where($where)
            ->order($order)
            ->page($page,10)
            ->select();
        //----------------加入购物车了没-----
        if($good){
            foreach ($good as $k=>$v){
                $good[$k]['haveNum'] = 0;
                $have = Db::table('up_shopping_car')
                    ->where('car_goodid', $v['g_id'])
                    ->where('car_userid', $user_id)
                    ->field('car_number')
                    ->find();
                if($have){
                    $good[$k]['haveNum'] = $have['car_number'];
                }
            }
        }
        //----------------加入购物车了没end-----
        return json_encode(['status'=>200,'good'=>$good]);
    }

    /**
     * 某个商品的评价列表：goodCommList
     * g_id，page
     * @return string
     */
    public function goodCommList(){
        extract(input());
        $auth = $this->checkAll($user_id, $time, $value, $reqKey);
        if ($auth == false) {
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        //2、此商品的最新的几个评论
        $field = 'comment_id,comment_goodid,comment_user_id,comment_score,comment_content,comment_time';
        $field .= ',comment_username,comment_image,user_username,user_image,user_phone';
        $pl = Db::table('up_good_comment')->alias('gc')
            ->join('up_u_user u','gc.comment_user_id=u.user_id','LEFT')
            ->where('comment_goodid', 'like',"%,$g_id,%")
            ->order('comment_time DESC')
            ->field($field)
            ->page($page,15)
            ->select();
        return json_encode(['status'=>200,'pl'=>$pl]);
    }
    /**
     * 某个商铺的所有评价：shopCommList
     * s_id，page
     * @return string
     */
    public function shopCommList(){
        extract(input());
        $auth = $this->checkAll($user_id, $time, $value, $reqKey);
        if ($auth == false) {
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        //2、此商品的最新的几个评论
        $field = 'comment_id,comment_goodid,comment_user_id,comment_score,comment_content,comment_time';
        $field .= ',comment_username,comment_image,user_username,user_image,user_phone';
        $pl = Db::table('up_good_comment')->alias('gc')
            ->join('up_u_user u','gc.comment_user_id=u.user_id','LEFT')
            ->where('comment_shopid', $s_id)
            ->order('comment_time DESC')
            ->field($field)
            ->page($page,15)
            ->select();
        return json_encode(['status'=>200,'pl'=>$pl]);
    }
    /**
     * 某个商家的商品详情
     * g_id 商品id
     * @return array 返回数组
     */
    public function shopGoodInfo(){
        extract(input());
        $auth = $this->checkAll($user_id, $time, $value, $reqKey);
        if ($auth == false) {
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        //1、商品信息
        $good = Db::table('up_goods')//存在即代表有抢购商品（秒杀）
            ->where('g_id', $g_id)
            ->find();
        //-------------广告图的商品有可能下架了------------------
        if($good['g_status'] != 1){
            return json_encode(['status'=>0,'msg'=>'此商品已下架']);
        }
        //-------------广告图的商品有可能下架了end------------------
        $good['type'] = Db::table('up_shop_type')->where('st_id', $good['g_type'])->value('st_name');
        $good['phone'] = Db::table('up_shops')->where('s_id', $good['g_shop'])->value('s_phone');
        if ($good['g_image']) {
            $good['g_image'] = explode(',', $good['g_image']);
        }
        //2、此商品的最新的几个评论
        $field = 'comment_id,comment_goodid,comment_user_id,comment_score,comment_content,comment_time';
        $field .= ',comment_username,comment_image,user_username,user_image,user_phone';
        $pl = Db::table('up_good_comment')->alias('gc')
            ->join('up_u_user u','gc.comment_user_id=u.user_id','LEFT')
            ->where('comment_goodid', 'like',"%,$g_id,%")
            ->order('comment_time DESC')
            ->field($field)
            ->page(1,3)
            ->select();
        //是不是买了，买了几份（UI上没有，以防万一）
        $have = Db::table('up_shopping_car')
            ->where('car_goodid', $g_id)
            ->where('car_userid', $user_id)
            ->field('car_number')
            ->find();
        $good['haveNum'] = 0;
        if($have){
            $good['haveNum'] = $have['car_number'];
        }
        return json_encode(['status'=>200,'good'=>$good,'pl'=>$pl,'buy'=>$good['haveNum']]);
    }

    /**
     * 加入购物车
     * g_id 商品id
     * type  1是加 2是减
     * @return array 返回数组
     */
    public function putGoodInCar(){
        extract(input());
        $auth = $this->checkAll($user_id, $time, $value, $reqKey);
        if ($auth == false) {
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        //1、商品信息
        $g = Db::table('up_goods')
            ->where('g_id', $g_id)
            ->field('g_shop,g_canbuy,g_stock')
            ->find();
        if($g['g_stock']==0){
            return json_encode(['status'=>0,'msg'=>'库存不足']);
        }
        //是不是买了，买了几份（UI上没有，以防万一）
        $buy = Db::table('up_shopping_car')
            ->where('car_goodid', $g_id)
            ->where('car_userid', $user_id)
            ->where('car_status', 1)
            ->find();
        if($buy){
            if($type == 1){
                if($g['g_canbuy']>0 && $buy['car_number'] >= $g['g_canbuy']){
                    return json_encode(['status'=>0,'msg'=>'只能限购'.$g['g_canbuy'].'份']);
                }
                if($g['g_stock']>0 && $buy['car_number'] >= $g['g_stock']){
                    return json_encode(['status'=>0,'msg'=>'库存不足']);
                }
                $res = Db::table('up_shopping_car')
                    ->where('car_goodid', $g_id)
                    ->where('car_userid', $user_id)
                    ->where('car_status', 1)
                    ->setInc('car_number');
            }else{
                if($buy['car_number'] <= 1){
                    $res = Db::table('up_shopping_car')
                        ->where('car_goodid', $g_id)
                        ->where('car_userid', $user_id)
                        ->where('car_status', 1)
                        ->delete();
                }else{
                    $res = Db::table('up_shopping_car')
                        ->where('car_goodid', $g_id)
                        ->where('car_userid', $user_id)
                        ->where('car_status', 1)
                        ->setDec('car_number');
                }
            }
        }else{
            if($type == 1) {
                $data = array();
                $data['car_shopid'] = $g['g_shop'];
                $data['car_goodid'] = $g_id;
                $data['car_userid'] = $user_id;
                $data['car_time'] = date('Y-m-d H:i:s');
                $res = Db::table('up_shopping_car')->insert($data);
            }else{
                return json_encode(['status'=>0,'msg'=>'不能小于0']);
            }
        }
        if($res){
            return json_encode(['status'=>200,'msg'=>'加入购物车成功']);
        }else{
            return json_encode(['status'=>0,'msg'=>'加入购物车失败']);
        }

    }
    /**
     * 选择收货地址
     *
     * @return array 返回数组
     */
    public function getAddress(){
        extract(input());
        $auth = $this->checkAll($user_id, $time, $value, $reqKey);
        if ($auth == false) {
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        //1、商品信息
        $address = Db::table('up_user_address')//存在即代表有抢购商品（秒杀）
            ->where('add_userid', $user_id)
            ->order('add_id DESC')
            ->select();
        return json_encode(['status'=>200,'msg'=>$address]);

    }
     /**
     * 某一个收货地址详情
     *$add_id
     * @return array 返回数组
     */
    public function getOneAddress(){
        extract(input());
        $auth = $this->checkAll($user_id, $time, $value, $reqKey);
        if ($auth == false) {
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        //1、商品信息
        $address = Db::table('up_user_address')//存在即代表有抢购商品（秒杀）
            ->where('add_id', $add_id)
            ->find();
        return json_encode(['status'=>200,'msg'=>$address]);

    }

    /**
     * @return string
     * 新增地址
     */
    public function addAddress(){
        extract(input());
        $auth = $this->checkAll($user_id, $time, $value, $reqKey);
        if ($auth == false) {
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $data = array();
        $data['add_userid'] = $user_id;
        $data['add_lat'] = $lat;
        $data['add_lon'] = $lon;
        $data['add_address'] = $address;
        $data['add_phone'] = $phone;
        $data['add_username'] = $name;
        $data['add_sex'] = $sex;
        $res = Db::table('up_user_address')->insert($data);
        if($res){
            return json_encode(['status'=>200,'msg'=>'成功']);
        }else{
            return json_encode(['status'=>0,'msg'=>'失败']);
        }

    }
    /**
     * @return string
     * 编辑地址
     */
    public function updateAddress(){
        extract(input());
        $auth = $this->checkAll($user_id, $time, $value, $reqKey);
        if ($auth == false) {
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $data = array();
        $data['add_userid'] = $user_id;
        $data['add_lat'] = $lat;
        $data['add_lon'] = $lon;
        $data['add_address'] = $address;
        $data['add_phone'] = $phone;
        $data['add_username'] = $name;
        $data['add_sex'] = $sex;
        $res = Db::table('up_user_address')->where('add_id',$add_id)->update($data);
        if($res){
            return json_encode(['status'=>200,'msg'=>'成功']);
        }else{
            return json_encode(['status'=>0,'msg'=>'失败']);
        }

    }
    /**
     * @return string
     * 删除地址
     */
    public function deleteAddress(){
        extract(input());
        $auth = $this->checkAll($user_id, $time, $value, $reqKey);
        if ($auth == false) {
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $res = Db::table('up_user_address')->where('add_id',$add_id)->delete();
        if($res){
            return json_encode(['status'=>200,'msg'=>'成功']);
        }else{
            return json_encode(['status'=>0,'msg'=>'失败']);
        }

    }

    /**
     * @return string
     * 设为默认
     */
    public function setAddress(){
        extract(input());
        $auth = $this->checkAll($user_id, $time, $value, $reqKey);
        if ($auth == false) {
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $res = Db::table('up_user_address')->where('add_userid',$user_id)->update(['add_type'=>1]);
        $res = Db::table('up_user_address')->where('add_id',$add_id)->update(['add_type'=>2]);
        if($res){
            return json_encode(['status'=>200,'msg'=>'成功']);
        }else{
            return json_encode(['status'=>0,'msg'=>'失败']);
        }

    }

}